package controller;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
// default
import dal.CauHoiDAO;
import dto.CauHoiDTO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// xử lý upload
import java.io.File;
import java.util.List;
import java.util.ListIterator;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

// xử lý xml
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

/**
 *
 * @author Tan Thanh, vantuan
 */
@WebServlet(name = "import_question", urlPatterns = {"/cauhoi_import"})
public class ImportQuestionController extends HttpServlet {

    private CauHoiDAO dao = null;

    public ImportQuestionController() {
        this.dao = new CauHoiDAO();
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Thi trắc nghiệm online</title>");
        out.println("</head>");
        out.println("<body>");
        try {
            // Check that we have a file upload request
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (!isMultipart) {
                throw new ServletException("Dùng sai dạng form");
            }

            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //factory.setSizeThreshold(1024); // yourMaxMemorySize
            //factory.setRepository(new java.io.File("C:/tempDir")); // yourTempDirectory

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            //upload.setSizeMax(2048); // yourMaxRequestSize

            // Parse the request
            List items = upload.parseRequest(request);
            ListIterator iterator = items.listIterator();
            while (iterator.hasNext()) // duyệt các param được upload
            {
                FileItem item = (FileItem) iterator.next();
                if (item.isFormField()) // param dạng input
                {
//                    String name = item.getFieldName();
//                    String value = item.getString("utf-8");
                } else // param dạng file
                {
                    String fileName = item.getName(); // tên file
                    String realPath = getServletContext().getRealPath(""); // lấy Root path trên server
                    String filePath = realPath + "/files/" + fileName; // đường dẫn lưu file
                    File file = new File(filePath); // tạo file theo đường dẫn
                    item.write(file); // ghi file

                    out.println("<h1>File upload successfully !</h1>");
                    out.println("<h3><i>Đường dẫn file đã upload : " + "/files/" + fileName + "</i></h3>");

                    /**
                     * ********** ĐỌC FILE XML VÀ GHI VÀO CSDL ***********
                     */
                    File fXmlFile = new File(filePath);
                    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                    Document doc = dBuilder.parse(fXmlFile);
                    doc.getDocumentElement().normalize();
                    //out.println("Root element : " + doc.getDocumentElement().getNodeName());

                    NodeList cauhoiList = doc.getElementsByTagName("Cauhoi");
                    int questionInsertCount = 0;
                    for (int i = 0; i < cauhoiList.getLength(); i++) {
                        Node cauhoiNode = cauhoiList.item(i);
                        if (cauhoiNode.getNodeType() == Node.ELEMENT_NODE) {
                            Element cauhoiElement = (Element) cauhoiNode;
                            NodeList noidung, luachon, dapan, dokho;
                            noidung = cauhoiElement.getElementsByTagName("Noidung");
                            luachon = cauhoiElement.getElementsByTagName("Luachon");
                            dapan = cauhoiElement.getElementsByTagName("Dapan");
                            dokho = cauhoiElement.getElementsByTagName("Dokho");

                            // create DTO object
                            CauHoiDTO info = new CauHoiDTO(
                                    noidung.item(0).getTextContent(),
                                    luachon.item(0).getTextContent(),
                                    luachon.item(1).getTextContent(),
                                    luachon.item(2).getTextContent(),
                                    luachon.item(3).getTextContent(),
                                    Integer.parseInt(dapan.item(0).getTextContent()),
                                    Integer.parseInt(dokho.item(0).getTextContent()));
                            if (dao.insertQuestion(info) == false) {
                                break;
                            }

                            questionInsertCount++;
                        }
                    }
                    out.println("<h1>File import successfully !</h1>");
                    out.println("<h3><i>Số lượng câu hỏi đã import : " + questionInsertCount + "</i></h3>");
                }
            }
        } catch (Exception e) {
            out.println("Exception : " + e.getMessage());
        } finally {
            out.println("<br/><a href='cauhoi.jsp'>Nhấn vào đây để trở lại</a><br/>Hoặc trình duyệt sẽ tự động chuyển sau");
            out.println("<div id='javascript_countdown_time'></div>");
            out.println("<script type='text/javascript' src='js/countdown.js'></script>");
            out.println("<script type='text/javascript'> "
                    + "timeleft_function = function() { window.location = 'cauhoi.jsp'; }; "
                    + "javascript_countdown.init(15, 'javascript_countdown_time'); "
                    + "</script>");
            out.println("</body>");
            out.println("</html>");
            out.close();
        }
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
